<template>
  <div class="search-container">
    <!-- 返回按钮 -->
    <div class="header">
      <div class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i> 返回
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-header">
      <van-search
          v-model="searchQuery"
          placeholder="搜索帖子标题或用户名..."
          shape="round"
          @search="performSearch"
          @clear="clearSearch"
      >
        <template #left-icon>
          <van-icon name="search" />
        </template>
      </van-search>
    </div>

    <!-- 搜索选项 -->
    <div class="search-options">
      <van-radio-group v-model="searchType" direction="horizontal">
        <van-radio name="title">按标题搜索</van-radio>
        <van-radio name="nickname">按用户搜索</van-radio>
      </van-radio-group>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results">
      <div v-if="loading" class="loading">
        <van-loading size="24px">搜索中...</van-loading>
      </div>

      <div v-else-if="searchResults.length === 0 && searchQuery" class="empty-state">
        <van-empty image="search" description="没有找到相关结果" />
      </div>

      <div v-else-if="searchResults.length > 0" class="results-list">
        <div class="results-count">找到 {{ total }} 条结果</div>

        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="loadMore"
        >
          <div
              v-for="(post, index) in searchResults"
              :key="index"
              class="post-item"
              @click="goToPostDetail(post.postId)"
          >
            <div class="post-header">
              <div class="user-info">
                <div class="avatar">
                  <van-image v-if="post.user.avatar" round width="45" height="45" :src="post.user.avatar" />
                  <van-icon v-else name="user-circle-o" size="45" color="#c8c9cc" />
                </div>
                <div class="name-time">
                  <div class="username">{{ post.user.nickname }}</div>
                  <div class="time">{{ formatTime(post.createAt) }}</div>
                </div>
              </div>
              <div class="post-type">
                <van-tag :type="getTagType(post.type)">{{ getTypeText(post.type) }}</van-tag>
              </div>
            </div>

            <div class="post-content">
              <h3 class="post-title">{{ post.title }}</h3>
              <p class="post-desc">{{ post.content }}</p>
            </div>

            <div class="post-stats">
              <div class="stat">
                <van-icon :name="post.isLiked ? 'like' : 'like-o'" />
                <span>{{ post.likeCount }}</span>
              </div>
              <div class="stat">
                <van-icon name="comment-o" />
                <span>{{ post.replyCount }}</span>
              </div>
              <div class="stat">
                <van-icon name="eye-o" />
                <span>{{ post.viewCount }}</span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <div v-else class="initial-state">
        <van-empty image="search" description="输入关键词搜索帖子" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import {
  Search,
  Icon,
  List,
  Loading,
  Tag,
  Empty,
  RadioGroup,
  Radio,
  Image,
  showToast
} from 'vant';

export default {
  name: 'SearchPage',
  components: {
    [Search.name]: Search,
    [Icon.name]: Icon,
    [List.name]: List,
    [Loading.name]: Loading,
    [Tag.name]: Tag,
    [Empty.name]: Empty,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Image.name]: Image,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();

    const searchQuery = ref('');
    const searchType = ref('title'); // 搜索类型：title, nickname, both
    const searchResults = ref([]);
    const loading = ref(false);
    const finished = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    // 从路由参数获取搜索关键词
    onMounted(() => {
      if (route.query.q) {
        searchQuery.value = route.query.q;
        performSearch();
      }
    });

    // 执行搜索
    const performSearch = async () => {
      if (!searchQuery.value.trim()) {
        showToast('请输入搜索内容');
        return;
      }

      // 重置状态
      searchResults.value = [];
      currentPage.value = 1;
      finished.value = false;

      // 更新URL
      router.replace({
        query: { ...route.query, q: searchQuery.value }
      });

      // 执行搜索
      await loadMore();
    };

    // 加载更多搜索结果
    const loadMore = async () => {
      if (finished.value || loading.value) return;

      loading.value = true;

      try {
        // 准备请求参数
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value
        };

        // 根据搜索类型添加不同的参数
        if (searchType.value === 'title' || searchType.value === 'both') {
          params.title = searchQuery.value;
        }

        if (searchType.value === 'nickname' || searchType.value === 'both') {
          params.nickname = searchQuery.value;
        }

        const response = await axios.get('/api/posts/search', { params });
        console.log(response.data)
        const data = response.data;
        const newResults = data.records || data.list || [];

        if (newResults.length === 0) {
          finished.value = true;
          return;
        }

        if (currentPage.value === 1) {
          searchResults.value = newResults;
        } else {
          searchResults.value = [...searchResults.value, ...newResults];
        }

        // 更新总条数
        total.value = data.total || newResults.length;

        // 检查是否还有更多数据
        if (newResults.length < pageSize.value) {
          finished.value = true;
        } else {
          currentPage.value += 1;
        }
      } catch (error) {
        console.error('搜索失败:', error);
        showToast('搜索失败，请重试');
      } finally {
        loading.value = false;
      }
    };

    // 清空搜索
    const clearSearch = () => {
      searchQuery.value = '';
      searchResults.value = [];
      currentPage.value = 1;
      finished.value = false;
    };

    // 跳转到帖子详情
    const goToPostDetail = (postId) => {
      router.push({
        name: 'postDetail',
        params: { id: postId }
      });
    };

    // 格式化时间
    const formatTime = (timeString) => {
      if (!timeString) return '';

      const time = new Date(timeString);
      const now = new Date();
      const diff = now - time;
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));

      if (days === 0) return '今天';
      if (days === 1) return '昨天';
      if (days < 7) return `${days}天前`;

      return time.toLocaleDateString();
    };

    // 获取帖子类型文本
    const getTypeText = (type) => {
      const types = {
        2: '讨论',
        3: '求助',
      };
      return types[type] || '未知';
    };

    // 获取标签类型
    const getTagType = (type) => {
      const types = {
        1: 'primary',
        2: 'warning',
        3: 'success'
      };
      return types[type] || 'default';
    };
    const goBack = () => {
      router.back();
    };

    return {
      searchQuery,
      searchType,
      searchResults,
      loading,
      finished,
      total,
      goBack,
      performSearch,
      clearSearch,
      goToPostDetail,
      formatTime,
      getTypeText,
      getTagType
    };
  }
}
</script>

<style scoped>
.search-container {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  min-height: 100vh;
  padding: 16px;
}

/* 返回按钮样式 */
.header {
  margin-bottom: 20px;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  padding: 10px 16px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #3A7BFF;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background-color: #f0f5ff;
  transform: translateX(-4px);
}

.back-btn i {
  margin-right: 8px;
}

/* 搜索头部样式 */
.search-header {
  margin-bottom: 16px;
}

.search-header .van-search {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 搜索选项样式 */
.search-options {
  background-color: white;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}
.like .van-icon {
  color: #ff5000;
}
.search-options .van-radio-group {
  display: flex;
  justify-content: center;
  gap: 24px;
}

.search-options .van-radio {
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
}

.search-options .van-radio--checked {
  background-color: #3A7BFF;
  color: white;
}



/* 搜索结果样式 */
.search-results {
  margin-top: 8px;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.results-count {
  font-size: 14px;
  color: #666;
  padding: 12px 0;
  text-align: center;
  background-color: white;
  border-radius: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.post-item {
  background-color: white;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.post-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: #3A7BFF;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar .van-icon {
  color: #a0a4a8;
}

.name-time {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 600;
  font-size: 16px;
  color: #2c3e50;
  margin-bottom: 4px;
}

.time {
  font-size: 12px;
  color: #969799;
}

.post-type {
  flex-shrink: 0;
}

.post-content {
  margin-bottom: 16px;
}

.post-title {
  font-size: 18px;
  font-weight: 700;
  margin-bottom: 12px;
  color: #2c3e50;
  line-height: 1.4;
}

.post-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-stats {
  display: flex;
  gap: 20px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.stat {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #969799;
  font-size: 13px;
  transition: color 0.3s ease;
}

.stat:hover {
  color: #3A7BFF;
}

.stat .van-icon {
  font-size: 16px;
}

.empty-state, .initial-state {
  margin-top: 60px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .search-container {
    padding: 12px;
  }

  .post-item {
    padding: 16px;
  }

  .post-title {
    font-size: 16px;
  }

  .search-options .van-radio-group {
    gap: 12px;
  }

  .search-options .van-radio {
    padding: 6px 12px;
    font-size: 14px;
  }
}

/* 动画效果 */
.post-item {
  animation: fadeInUp 0.5s ease forwards;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 滚动条样式 */
.results-list {
  scrollbar-width: thin;
  scrollbar-color: #3A7BFF #f5f7fa;
}

.results-list::-webkit-scrollbar {
  width: 6px;
}

.results-list::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 3px;
}

.results-list::-webkit-scrollbar-thumb {
  background-color: #3A7BFF;
  border-radius: 3px;
}
</style>